#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/22 22:08
# @Author  : leon yan
# @Site    : 
# @File    : Plc.py
# @Software: PyCharm
from enum import Enum  # 枚举类型

from PyQt5.QtCore import QItemSelectionModel, Qt
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QBrush, QColor
from PyQt5.QtWidgets import (QApplication, QWidget,
                             QAbstractItemView)

import Globalist as gl
from lib.qpulsesignal import Qpulsesignal
from lib.qtabdelegates import EmptyDelegate, QmyComboBoxDelegate, QmyFloatSpinDelegate
from resource.Plc_ui import Ui_Form


class QTableHeader(Enum):
    """PlcMonitor"""
    PlcMonitor = ["Plc_Num", "+0", "+1", "+2", "+3", "+4", "+5", "+6", "+7", "+8", "+9",
                  "+10", "+11", "+12", "+13", "+14", "+15", "+16", "+17", "+18", "+19", "+20", "+21", "+22", "+23"]
    PlcMonitor_Width = [260, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60]


class QPlc(QWidget, Ui_Form):
    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        ''''''
        '''启动脉冲线程'''
        self.PulseSignal = Qpulsesignal()
        self.PulseSignal.start()
        self.PulseSignal.bPulse.connect(self.do_UpdateStatus)

        self.comboDelegate1 = QmyComboBoxDelegate(self)
        self.comboDelegate2 = QmyComboBoxDelegate(self)
        self.COL_COUNT = 0
        self.itemModel = QStandardItemModel(0, 0, self)  # 数据模型,1行3列
        self.selectionModel = QItemSelectionModel(self.itemModel)  # Item选择模型
        ''''''
        self.strTableName = None
        self.typeName = None
        # 创建自定义代理组件并设置
        self.spinDevice = QmyFloatSpinDelegate(0, 20000, 0, self)  # 设备参数
        self.spinLength = QmyFloatSpinDelegate(0, 6000, 2, self)  # 未用
        self.spinDegree = QmyFloatSpinDelegate(1, 359, 1, self)  # 未用
        ''''''
        self.setBtnText()

    def setBtnText(self):
        aa = gl.global_var["Plc_read_area"]     # 最多14个KEY(14个按钮)
        j = 1
        for k, v in aa.items():
            if j <= 11:
                exec("self.btn" + str(j) + ".setText('" + str(k) + "')")
                exec("self.btn" + str(j) + ".clicked.connect(self.doManualClicked)")
            j += 1
        if j < 15:
            for i in range(j, 15, 1):
                exec("self.btn" + str(i) + ".setVisible(False)")
        self.btn1.setStyleSheet("background-color: rgb(129, 206, 128);")
        self.setTableSheet("PlcMonitor", self.btn1.text())

    def doManualClicked(self):
        aa = eval("self." + str(self.sender().objectName()) + ".text()")
        for i in range(14):
            if self.sender().objectName() == "btn" + str(i+1):
                exec("self." + self.sender().objectName() + ".setStyleSheet('background-color: rgb(129, 206, 128);')")
            else:
                exec("self.btn" + str(i + 1) + ".setStyleSheet('background-color: rgb(230, 230, 230);')")
        self.setTableSheet("PlcMonitor", aa)

    def setTableSheet(self, strTableName, typeName):
        self.strTableName = strTableName
        self.typeName = typeName
        headerList = QTableHeader[strTableName].value
        headerWidth = QTableHeader[strTableName + "_Width"].value
        if strTableName == "PlcMonitor":
            for i in range(11):
                self.tableView.setItemDelegateForColumn(i, EmptyDelegate(self))
        else:
            return
        self.COL_COUNT = len(headerList)
        self.itemModel = QStandardItemModel(0, self.COL_COUNT, self)  # 数据模型,1行3列
        self.itemModel.setHorizontalHeaderLabels(headerList)  # 设置表头文字
        self.selectionModel = QItemSelectionModel(self.itemModel)  # Item选择模型
        # self.selectionModel.currentChanged.connect(self.do_currentChanged)
        # self.tableView.doubleClicked.connect(self.edtRow)

        headColTab = self.tableView.horizontalHeader()
        headColTab.setStyleSheet("QHeaderView::section{background:#454545;color:#ffffff; font: 9pt 3ds;}")
        headRowTab = self.tableView.verticalHeader()
        headRowTab.setStyleSheet("QHeaderView::section{background:#454545;color:#ffffff}")

        # 为tableView设置数据模型
        self.tableView.setModel(self.itemModel)  # 设置数据模型
        self.tableView.setSelectionModel(self.selectionModel)  # 设置选择模型

        # oneOrMore = QAbstractItemView.ExtendedSelection
        # self.tableView.setSelectionMode(oneOrMore)  # 可多选

        itemOrRow = QAbstractItemView.SelectItems
        self.tableView.setSelectionBehavior(itemOrRow)  # 单元格选择

        self.tableView.verticalHeader().setDefaultSectionSize(22)  # 缺省行高
        self.tableView.setEnabled(True)  # tableView使能，默认是使能的
        for i in range(self.COL_COUNT):
            self.tableView.horizontalHeader().resizeSection(i, headerWidth[i])

        '''生成表格'''
        self.fileToTable()

    def __del__(self):
        print("Plc is deleted")

    def fileToTable(self, strListData=None):
        if not strListData:
            return
        lst = strListData
        if lst is None or lst == []:
            return
        else:
            for i in range(len(lst)):
                for j in range(self.COL_COUNT):
                    if len(lst[i]) > j:
                        aa = str(lst[i][j])
                        item = QStandardItem(aa)
                        # 设置每个位置的文本值
                        self.itemModel.setItem(i, j, item)
                        item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

    '''与PLC的交互'''

    def do_UpdateStatus(self):
        # aa = self.itemModel.rowCount()
        plcIpDict = gl.global_var["deviceIpDict"]
        if self.strTableName == "PlcMonitor":
            aa = gl.global_var["Plc_read_area"][self.typeName]["dArea"]
            i = 0
            for key, value in aa.items():
                item = QStandardItem(" Plc_" + key + " (" + plcIpDict[int(key)][0] + ")" + "_" + str(value[0]) + str(value[1]))
                self.itemModel.setItem(i, 0, item)
                for j in range(len(value[2])):
                    item = QStandardItem(str(value[2][j]))
                    self.itemModel.setItem(i, j + 1, item)
                    item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                if len(value[2]) < 20:
                    eStart = len(value[2]) + 1
                    for k in range(eStart, 20, 1):
                        item = QStandardItem("")
                        self.itemModel.setItem(i, k + 1, item)
                i += 1

    def readListTable(self):
        rowCount = self.itemModel.rowCount()
        colCount = self.COL_COUNT
        strTabList = []
        for i in range(rowCount):
            strRowList = []
            for j in range(colCount):
                cellItem = self.itemModel.item(i, j)
                strRowList.append(cellItem.text())
            strTabList.append(strRowList)
        return strTabList


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    windowObj = QPlc()

    windowObj.show()
    sys.exit(app.exec_())
